package com.pms.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.cache.utils.RedisCacheUtil;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.IMemberService;
import com.pms.service.IEstateAgencyService;
import com.pms.service.IHouseMasterInfoService;
import com.pms.service.IOwnerMemberService;
import com.pms.service.IUnitHouseService;
import com.pms.util.DateUtil;
import com.pms.util.ValidateUtil;
import com.pms.util.idutil.CodeGenerate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 1） 查询房屋 不根据 物业，社区分开，终端自行过滤。
 * 2） 默认房屋 只有1个，isDefault等于2。
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-26
 */
@RestController
@RequestMapping("/ownerMember")
@Api(value = "会员认证户室相关接口", description = "会员认证户室相关接口")
public class OwnerMemberApiController extends BaseController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IOwnerMemberService ownerMemberService;
    @Autowired
    private IHouseMasterInfoService houseMasterInfoService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @ApiOperation(value = "业主认证/物业管理员申请")
    @RequestMapping(value = "/validateHouseByPhone", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityId", value = "小区id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "houseId", value = "户室id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "fourPhone", value = "手机号后4位,验证业主必需", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "memberName", value = "会员名称,验证管理员必需", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "memberPhone", value = "会员联系号码,验证管理员必需", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "isReadMyHouse", value = "是(1)/否(2-默认)查询并返回我的户室", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "isReadHouseByAgency", value = "是(1-默认)/否(2)只查询物业机构下的户室", required = false, dataType = "int", paramType = "form"),
    })
    public R validateHouseByPhone(Long communityId, Long houseId, Long memberId
            , String fourPhone, String memberName, String memberPhone, Integer isReadMyHouse, Integer isReadHouseByAgency) {
        parameterIsNull(communityId, "社区id不能为空");
        parameterIsNull(memberId, "户室id不能为空");
        parameterIsNull(houseId, "会员id不能为空");
        EstateAgency community = agencyService.selectById(communityId);
        parameterIsNull(community, "未查询到社区相关信息");
        UnitHouse house = unitHouseService.selectById(houseId);
        if (house == null) {
            return R.error(400, "未查询到户室信息");
        }
        if (!house.getCommunityId().equals(communityId)) {
            return R.error(400, "户室与社区不匹配");
        }
        boolean estateHouseTag = false;
        if (house.getIsEstateHouse() == 1) {
            estateHouseTag = true;
            parameterIsBlank(memberName, "请填写名称");
            parameterIsBlank(memberPhone, "请填写联系电话");
            if (!ValidateUtil.validatePhone(memberPhone)) {
                return R.error(400, "请填写正确的手机联系方式");
            }
        }
        if (!estateHouseTag) {
            parameterIsBlank(fourPhone, "请填写户主手机号后四位");
            fourPhone = fourPhone.trim();
            if (fourPhone.length() != 4) {
                if (!ValidateUtil.validatePhone(fourPhone)) {
                    return R.error(400, "请填写户主完整手机号或手机号后四位");
                }
                fourPhone = fourPhone.substring(fourPhone.length() - 4, fourPhone.length());
            }
        }
        MemberInfo memberInfo = memberService.queryBymember(memberId);
        if (null == memberInfo) {
            return R.error(400, "未查询到会员相关信息");
        }
        if(StringUtils.isNotBlank(memberInfo.getNickName())){
            memberInfo.setNickName("");
        }
        Wrapper<OwnerMember> oldOwWp = new EntityWrapper<OwnerMember>();
        oldOwWp.eq("house_id", houseId);
        oldOwWp.eq("member_id", memberId);
        oldOwWp.eq("community_id", communityId);
        oldOwWp.orderBy("owner_id", true);
        OwnerMember oldOw = ownerMemberService.selectOne(oldOwWp);
        if (null != oldOw) {
            return R.error(400, "你已认证该户室");
        }
        if (estateHouseTag) {
            OwnerMember insertOm = new OwnerMember();
            insertOm.setAgencyId(house.getAgencyId());
            insertOm.setCommunityId(house.getCommunityId());
            insertOm.setFloorId(house.getFloorId());
            insertOm.setHouseId(house.getHouseId());
            insertOm.setUnitId(house.getUnitId());
            insertOm.setMemberId(memberId);
            insertOm.setUnitName(house.getUnitName());
            insertOm.setHouseName(house.getHouseNumber());
            insertOm.setCreateTime(new Date());
            insertOm.setCommunityName(community.getAgencyName());
            insertOm.setIsDefault(1);//不设 默认房屋
            insertOm.setType(2);//设置 类型为 管理员带审核
            if(StringUtils.isBlank(memberPhone)){
                memberPhone = memberInfo.getPhone();
            }
            insertOm.setOwnerPhone(memberPhone);
            if(StringUtils.isBlank(memberName)){
                memberName = memberInfo.getNickName();
            }
            insertOm.setReferrerId(-1L);
            insertOm.setOwnerName(memberName);
            insertOm.setReferrerNikeName("");//设置邀请人 昵称
            ownerMemberService.insert(insertOm);
            return R.ok("我们将尽快为您审核,请耐心等待");
        }
        if (!estateHouseTag) {
            Wrapper<HouseMasterInfo> houseMasterInfoWp = new EntityWrapper<HouseMasterInfo>();
            houseMasterInfoWp.eq("house_id", houseId);
            houseMasterInfoWp.eq("community_id", communityId);
            oldOwWp.orderBy("house_master_id", true);
            HouseMasterInfo houseMasterInfo = houseMasterInfoService.selectOne(houseMasterInfoWp);
            if (houseMasterInfo == null) {
                return R.error(400, "该户室未导入户主信息,请联系物业管理员");
            }
            String houseMasterFourPhone = null;
            if (StringUtils.isNotBlank(houseMasterInfo.getHouseMasterPhone())) {
                houseMasterFourPhone = houseMasterInfo.getHouseMasterPhone().substring(houseMasterInfo.getHouseMasterPhone().length() - 4, houseMasterInfo.getHouseMasterPhone().length());
            }
            if (null == houseMasterFourPhone) {
                if (StringUtils.isBlank(houseMasterInfo.getHouseMasterTelphone())) {
                    return R.error(400, "该户室户主信息有误，请联系物业管理员");
                }
                houseMasterFourPhone = houseMasterInfo.getHouseMasterTelphone().substring(houseMasterInfo.getHouseMasterTelphone().length() - 4, houseMasterInfo.getHouseMasterTelphone().length());
            }
            if (!houseMasterFourPhone.equals(fourPhone)) {
                return R.error(400, "认证失败");
            }
            OwnerMember insertOm = new OwnerMember();
            insertOm.setAgencyId(house.getAgencyId());
            insertOm.setCommunityId(house.getCommunityId());
            insertOm.setFloorId(house.getFloorId());
            insertOm.setHouseId(house.getHouseId());
            insertOm.setUnitId(house.getUnitId());
            insertOm.setMemberId(memberId);
            insertOm.setUnitName(house.getUnitName());
            insertOm.setHouseName(house.getFloorSort() + "楼" + house.getHouseNumber());
            insertOm.setCreateTime(new Date());
            insertOm.setIsDefault(1);//不设 默认房屋
            insertOm.setType(1);//设置 类型为 业主
            insertOm.setCommunityName(community.getAgencyName());
            insertOm.setOwnerPhone(memberInfo.getPhone());
            insertOm.setOwnerName(memberInfo.getNickName());
            insertOm.setReferrerId(-1L);
            insertOm.setReferrerNikeName("");//设置邀请人 昵称
            ownerMemberService.insert(insertOm);
        }
        //修改 户室 为已有会员入驻
        UnitHouse editHouse = new UnitHouse();
        editHouse.setIsHaveMember(2);
        unitHouseService.update(editHouse,new EntityWrapper<UnitHouse>().eq("house_id",houseId));
        if (isReadMyHouse == null || isReadMyHouse != 1) {
            isReadMyHouse = 2; //默认不查询 我的户室
        }
        if (isReadHouseByAgency == null || isReadHouseByAgency != 2) {
            isReadHouseByAgency = 1;//默认只查询物业机构的
        }
        if (isReadMyHouse == 1) {
            Long agencyId = null;
            if (isReadHouseByAgency == 1) {
                agencyId = house.getAgencyId();
            }
            List<Map<String, Object>> myHouseList = getMemberHouse(memberId, agencyId);
            return R.ok().put("data", myHouseList).putDescription(myHouseDescription());
        }
        return R.ok();
    }

    @ApiOperation(value = "生成户室认证邀请码")
    @RequestMapping(value = "/createValidateHouseInviteCode", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "communityId", value = "小区id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "houseId", value = "户室id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
    })
    public R createValidateHouseInviteCode(Long communityId, Long houseId, Long memberId) {
        parameterIsNull(communityId, "社区id不能为空");
        parameterIsNull(memberId, "户室id不能为空");
        parameterIsNull(houseId, "会员id不能为空");
        MemberInfo memberInfo = memberService.queryBymember(memberId);
        if (null == memberInfo) {
            return R.error(400, "未查询到会员相关信息");
        }
        EstateAgency community = agencyService.selectById(communityId);
        parameterIsNull(community, "未查询到社区相关信息");
        UnitHouse house = unitHouseService.selectById(houseId);
        if (house == null) {
            return R.error(400, "未查询到户室信息");
        }
        if (!house.getCommunityId().equals(communityId)) {
            return R.error(400, "户室与社区不匹配");
        }
        boolean estateHouseTag = false;
        if (house.getIsEstateHouse() == 1) {
            estateHouseTag = true;
        }
        Wrapper<OwnerMember> oldOwWp = new EntityWrapper<OwnerMember>();
        oldOwWp.eq("house_id", houseId);
        oldOwWp.eq("member_id", memberId);
        oldOwWp.eq("community_id", communityId);
        if (estateHouseTag) {
            oldOwWp.eq("type_", 3);//物业管理员
        }
        if (!estateHouseTag) {
            oldOwWp.eq("type_", 1);//业主
        }
        oldOwWp.orderBy("owner_id", true);
        OwnerMember oldOw = ownerMemberService.selectOne(oldOwWp);
        if (null == oldOw) {
            return R.error(400, "您尚未认证该户室，无法邀请");
        }
        if (oldOw.getType() != 1 && oldOw.getType() != 3) {
            return R.error(400, "权限不足");
        }
        String validateHouseInviteCode = getInviteCode();//生成邀请码
        Map<String, Object> varMap = new HashMap<String, Object>();
        varMap.put("houseId", houseId);
        varMap.put("houseInviteCode", validateHouseInviteCode);
        varMap.put("houseInviteMemberId", memberId);
        varMap.put("houseCommunityName", community.getAgencyName());
        varMap.put("houseTag", estateHouseTag);
        varMap.put("houseCommunityId", communityId);
        if(StringUtils.isBlank(memberInfo.getNickName())){
            memberInfo.setNickName("");
        }
        varMap.put("houseInviteMemberNickName", memberInfo.getNickName());
        redisCacheUtil.saveAndUpdate("validateHouseByInviteCode:" + validateHouseInviteCode, varMap, 600);//设置10分钟有效时间
        return R.ok().put("data", validateHouseInviteCode);
    }


    @ApiOperation(value = "邀请码认证 家庭成员/物业人员")
    @RequestMapping(value = "/validateHouseByInviteCode", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "isReadMyHouse", value = "是(1)/否(2-默认)查询并返回我的户室", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "isReadHouseByAgency", value = "是(1-默认)/否(2)只查询物业机构下的户室", required = false, dataType = "int", paramType = "form"),
    })
    public R validateHouseByInviteCode(Long memberId, String inviteCode, Integer isReadMyHouse, Integer isReadHouseByAgency) {
        parameterIsNull(memberId, "会员id不能为空");
        parameterIsBlank(inviteCode, "请填写邀请码");
        inviteCode = inviteCode.trim();
        Map<String, Object> codeMap = (Map<String, Object>)  redisCacheUtil.getVlue("validateHouseByInviteCode:" + inviteCode);
        if (null == codeMap) {
            return R.error(400, "邀请码错误");
        }
        Long inviteMemberId = null;
        Long houseId = null;
        Long communityId = null;
        String communityName = null;
        Boolean houseTag = null;
        String inviteMemberNickName = null;
        try {
            inviteMemberId = Long.parseLong(codeMap.get("houseInviteMemberId").toString());
            houseId = Long.parseLong(codeMap.get("houseId").toString());
            houseTag = Boolean.parseBoolean(codeMap.get("houseTag").toString());
            communityName = codeMap.get("houseCommunityName").toString();
            communityId = Long.parseLong(codeMap.get("houseCommunityId").toString());
            inviteMemberNickName = codeMap.get("houseInviteMemberNickName").toString();
        } catch (NullPointerException ex) {
            return R.error(400, "邀请码错误");
        } catch (NumberFormatException ex) {
            return R.error(400, "邀请码错误");
        }
        // 验证 该户室 业主是否删除房屋
        Wrapper<OwnerMember> inviteMemberWp = new EntityWrapper<OwnerMember>();
        inviteMemberWp.eq("house_id", houseId);
        inviteMemberWp.eq("member_id", inviteMemberId);
        inviteMemberWp.eq("community_id", communityId);
        if (houseTag) {
            inviteMemberWp.eq("type_", 3);//物业管理员
        }
        if (!houseTag) {
            inviteMemberWp.eq("type_", 1);//业主
        }
        inviteMemberWp.orderBy("owner_id", true);
        OwnerMember inviteMemberOm = ownerMemberService.selectOne(inviteMemberWp);
        if (null == inviteMemberOm) {
            return R.error(400, "邀请码已失效");
        }
        MemberInfo memberInfo = memberService.queryBymember(memberId);
        if (null == memberInfo) {
            return R.error(400, "未查询到会员相关信息");
        }
        if(StringUtils.isNotBlank(memberInfo.getNickName())){
            memberInfo.setNickName("");
        }
        Wrapper<OwnerMember> currentMemberWp = new EntityWrapper<OwnerMember>();
        currentMemberWp.eq("house_id", houseId);
        currentMemberWp.eq("member_id", memberId);
        currentMemberWp.eq("community_id", communityId);
        OwnerMember currentMemberOw = ownerMemberService.selectOne(currentMemberWp);
        if (currentMemberOw != null) {
            return R.error(400, "该户室您已认证或申请");
        }
        OwnerMember insertOm = new OwnerMember();
        insertOm.setAgencyId(inviteMemberOm.getAgencyId());
        insertOm.setCommunityId(inviteMemberOm.getCommunityId());
        insertOm.setCommunityName(communityName);
        insertOm.setFloorId(inviteMemberOm.getFloorId());
        insertOm.setHouseId(inviteMemberOm.getHouseId());
        insertOm.setUnitId(inviteMemberOm.getUnitId());
        insertOm.setUnitName(inviteMemberOm.getUnitName());
        insertOm.setMemberId(memberId);
        insertOm.setCreateTime(new Date());
        insertOm.setIsDefault(1);//不设 默认房屋
        if (houseTag) {
            insertOm.setType(5);//设置 类型为 物业人员
        }
        if (!houseTag) {
            insertOm.setType(4);//设置 类型为 家庭成员
        }
        insertOm.setReferrerId(inviteMemberId);//设置邀请人
        insertOm.setReferrerNikeName(inviteMemberNickName);//设置邀请人 昵称
        insertOm.setHouseName(inviteMemberOm.getHouseName());
        insertOm.setOwnerName(memberInfo.getNickName());// 默认 为会员昵称
        insertOm.setOwnerPhone(memberInfo.getPhone());// 默认 为会员手机号
        ownerMemberService.insert(insertOm);
        redisCacheUtil.clearByKey("validateHouseByInviteCode:" + inviteCode);
        if (isReadMyHouse == null || isReadMyHouse != 1) {
            isReadMyHouse = 2; //默认不查询 我的户室
        }
        if (isReadHouseByAgency == null || isReadHouseByAgency != 2) {
            isReadHouseByAgency = 1;//默认只查询物业机构的
        }
        if (isReadMyHouse == 1) {
            Long agencyId = null;
            if (isReadHouseByAgency == 1) {
                agencyId = inviteMemberOm.getAgencyId();
            }
            List<Map<String, Object>> myHouseList = getMemberHouse(memberId, agencyId);
            return R.ok().put("data", myHouseList).putDescription(myHouseDescription());
        }
        return R.ok();
    }

    @ApiOperation(value = "删除我认证的户室")
    @RequestMapping(value = "/delMyHouse", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseId", value = "户室id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "isReadMyHouse", value = "是(1)/否(2-默认)查询并返回我的户室", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "isReadHouseByAgency", value = "是(1-默认)/否(2)只查询物业机构下的户室", required = false, dataType = "int", paramType = "form"),
    })
    public R delMyHouse(Long memberId, Long houseId, Integer isReadMyHouse, Integer isReadHouseByAgency) {
        parameterIsNull(memberId, "会员id不能为空");
        parameterIsNull(houseId, "户室id不能为空");
        Wrapper<OwnerMember> currentMemberWp = new EntityWrapper<OwnerMember>();
        currentMemberWp.eq("house_id", houseId);
        currentMemberWp.eq("member_id", memberId);
        OwnerMember currentMemberOw = ownerMemberService.selectOne(currentMemberWp);
        if (currentMemberOw == null) {
            return R.error(400, "你尚未认证该户室");
        }
        if (currentMemberOw.getType() == 2) {// 物业管理员申请
            return R.error(400, "请等待耐心物业管理员审核");
        }
        if (currentMemberOw.getType() == 3 || currentMemberOw.getType() == 5) {
            return R.error(400, "您没有删除权限,请联系物业管理员");
        }
        List<OwnerMember> currentMemberUnderMemberOmList = null;
        ownerMemberService.deleteById(currentMemberOw.getOwnerId());//删除 当前房屋
        // 删除 邀请的人员
        if (currentMemberOw.getType() == 1 || currentMemberOw.getType() == 3) {// 业主 或者 物业管理员
            Wrapper<OwnerMember> currentMemberUnderMemberWp = new EntityWrapper<OwnerMember>();
            currentMemberUnderMemberWp.eq("house_id", houseId);
            currentMemberUnderMemberWp.eq("referrer_id", memberId);
            if (currentMemberOw.getType() == 1) {
                currentMemberUnderMemberWp.eq("type_", 4);//删除 家庭成员
            }
            if (currentMemberOw.getType() == 3) {
                currentMemberUnderMemberWp.eq("type_", 5);//删除 物业人员
            }
            ownerMemberService.delete(currentMemberUnderMemberWp);
            //修改 户室 为无会员入驻
            UnitHouse editHouse = new UnitHouse();
            editHouse.setIsHaveMember(2);
            unitHouseService.update(editHouse,new EntityWrapper<UnitHouse>().eq("house_id",houseId));
        }
        if (isReadMyHouse == null || isReadMyHouse != 1) {
            isReadMyHouse = 2; //默认不查询 我的户室
        }
        if (isReadHouseByAgency == null || isReadHouseByAgency != 2) {
            isReadHouseByAgency = 1;//默认只查询物业机构的
        }
        if (isReadMyHouse == 1) {
            Long agencyId = null;
            if (isReadHouseByAgency == 1) {
                agencyId = currentMemberOw.getAgencyId();
            }
            List<Map<String, Object>> myHouseList = getMemberHouse(memberId, agencyId);
            if(myHouseList==null){
                myHouseList = new ArrayList<Map<String, Object>>();
            }
            return R.ok().put("data", myHouseList).putDescription(myHouseDescription());
        }
        return R.ok();
    }

    @ApiOperation(value = "删除我的家庭成员")
    @RequestMapping(value = "/delFamilyMember", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseId", value = "户室id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "familyMemberId", value = "家庭成员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "isReadMyFamilyMember", value = "是(1)/否(2-默认)查询并返回我的家庭成员", required = false, dataType = "int", paramType = "form"),
    })
    public R delFamilyMember(Long memberId, Long houseId, Long familyMemberId,Integer isReadMyFamilyMember) {
        parameterIsNull(memberId, "会员id不能为空");
        parameterIsNull(houseId, "户室id不能为空");
        parameterIsNull(familyMemberId, "请选择你要删除的家庭成员");
        Wrapper<OwnerMember> currentMemberWp = new EntityWrapper<OwnerMember>();
        currentMemberWp.eq("house_id", houseId);
        currentMemberWp.eq("referrer_id", memberId);
        currentMemberWp.eq("member_id", familyMemberId);
        OwnerMember currentMemberOw = ownerMemberService.selectOne(currentMemberWp);
        if (currentMemberOw == null) {
            return R.error(400, "您尚未邀请该成员!");
        }
        ownerMemberService.deleteById(currentMemberOw.getOwnerId());
        if(isReadMyFamilyMember==null||isReadMyFamilyMember!=1){
            isReadMyFamilyMember = 2;//默认不查询
        }
        if(isReadMyFamilyMember==1){
            List<Map<String, Object>> returnMap = getFamilyMember(memberId, houseId);
            if(returnMap==null){
                returnMap = new ArrayList<Map<String, Object>>();
            }
            return R.ok().put("data", returnMap).putDescription(myFamilyMemberDescription());
        }
        return R.ok();
    }

    @ApiOperation(value = "查询我的家庭成员")
    @RequestMapping(value = "/readMyFamilyMember", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseId", value = "当前户室id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
    })
    public R readMyFamilyMember(Long memberId, Long houseId) {
        parameterIsNull(memberId, "会员id不能为空");
        parameterIsNull(houseId, "户室id不能为空");
        Wrapper<OwnerMember> currentMemberWp = new EntityWrapper<OwnerMember>();
        currentMemberWp.eq("house_id", houseId);
        currentMemberWp.eq("member_id", memberId);
        OwnerMember currentMemberOw = ownerMemberService.selectOne(currentMemberWp);
        if (currentMemberOw == null) {
            return R.error(400, "您尚未认证该户室");
        }
        if (currentMemberOw.getType() != 1 && currentMemberOw.getType() != 3) {
            return R.error(400, "您没有权限");
        }
        List<Map<String, Object>> returnMap = getFamilyMember(memberId, houseId);
        return R.ok().put("data", returnMap).putDescription(myFamilyMemberDescription());
    }

    @ApiOperation(value = "查询我的房屋")
    @RequestMapping(value = "/readMyHouse", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "agencyId", value = "物业机构id", required = false, dataType = "long", paramType = "form"),
    })
    public R readMyHouse(Long memberId, Long agencyId) {
        parameterIsNull(memberId, "会员id不能为空");
        MemberInfo memberInfo = memberService.queryBymember(memberId);
        parameterIsNull(memberInfo, "未查询到会员信息");
        if (null != agencyId) {
            EstateAgency agency = agencyService.selectById(agencyId);
            parameterIsNull(agency, "未查询到物业信息");
        }
        List<Map<String, Object>> myHouseList = getMemberHouse(memberId, agencyId);
        return R.ok().put("data", myHouseList).putDescription(myHouseDescription());
    }

    @ApiOperation(value = "设置默认房屋")
    @RequestMapping(value = "/setDefaultHouse", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "houseId", value = "户室id", required = true, dataType = "long", paramType = "form"),
    })
    public R setDefaultHouse(Long memberId, Long houseId) {
        parameterIsNull(memberId, "会员id不能为空");
        parameterIsNull(houseId, "户室id不能为空");
        Wrapper<OwnerMember> currentMemberWp = new EntityWrapper<OwnerMember>();
        currentMemberWp.eq("house_id", houseId);
        currentMemberWp.eq("member_id", memberId);
        OwnerMember currentMemberOw = ownerMemberService.selectOne(currentMemberWp);
        parameterIsNull(currentMemberOw, "你尚未认证该户室");
        if(currentMemberOw.getIsDefault()==2){
            return R.error(400,"该户室已是默认户室");
        }
        currentMemberOw.setIsDefault(2);// 设置为默认房屋
        OwnerMember editDefalutOm = new OwnerMember();
        editDefalutOm.setIsDefault(1);
        ownerMemberService.update(editDefalutOm,new EntityWrapper<OwnerMember>().eq("member_id",memberId));
        ownerMemberService.updateById(currentMemberOw);
        return R.ok();
    }

    /**
     * 查询 会员的房屋 未根据机构id区分
     *
     * @param memberId 会员id
     * @param agencyId 物业机构id
     * @return
     */
    public List<Map<String, Object>> getMemberHouse(Long memberId, Long agencyId) {
        List<Map<String, Object>> memberHouseList = new ArrayList<Map<String, Object>>();
        Wrapper<OwnerMember> memberHouseWp = new EntityWrapper<OwnerMember>();
        memberHouseWp.eq("member_id", memberId);
        if (null != agencyId) {
            memberHouseWp.eq("agency_id", agencyId);
        }
        memberHouseWp.orderBy("is_default", false);// 默认房屋 在前
        memberHouseWp.orderBy("agency_id", true);// 根据物业机构id升序
        memberHouseWp.orderBy("community_id", true);// 根据社区id升序
        List<OwnerMember> familyMemberOmList = ownerMemberService.selectList(memberHouseWp);
        OwnerMember defalutHouseOm = null;
        boolean defalutHouseOmTag = true; //标记判断第一个 是不是默认户室
        if (null != familyMemberOmList&&!familyMemberOmList.isEmpty()) {
            for (int x = 0; x < familyMemberOmList.size(); x++) {
                if (familyMemberOmList.get(x).getType() != 2) {//排除物业管理员申请
                    if(!defalutHouseOmTag){
                        Map<String, Object> memberHouseMap = new HashMap<String, Object>();
                        memberHouseMap.put("communityId", familyMemberOmList.get(x).getCommunityId());
                        memberHouseMap.put("communityName", familyMemberOmList.get(x).getCommunityName());
                        memberHouseMap.put("houseId", familyMemberOmList.get(x).getHouseId());
                        memberHouseMap.put("houseName", familyMemberOmList.get(x).getUnitName() + familyMemberOmList.get(x).getHouseName());
                        memberHouseMap.put("agencyId", familyMemberOmList.get(x).getAgencyId());
                        memberHouseMap.put("isDefault",1);
                        memberHouseList.add(memberHouseMap);
                    }
                    if(defalutHouseOmTag){
                        defalutHouseOm =  familyMemberOmList.get(x);
                        if(defalutHouseOm.getIsDefault()!=2){//不是默认房屋
                            defalutHouseOm.setIsDefault(2);
                            OwnerMember editDefalutOm = new OwnerMember();
                            editDefalutOm.setIsDefault(1);
                            ownerMemberService.update(editDefalutOm,new EntityWrapper<OwnerMember>().eq("member_id",memberId));
                            ownerMemberService.updateById(defalutHouseOm);
                        }
                        Map<String, Object> memberDefalutHouseMap = new HashMap<String, Object>();
                        memberDefalutHouseMap.put("communityId", defalutHouseOm.getCommunityId());
                        memberDefalutHouseMap.put("communityName", defalutHouseOm.getCommunityName());
                        memberDefalutHouseMap.put("houseId", defalutHouseOm.getHouseId());
                        memberDefalutHouseMap.put("houseName",defalutHouseOm.getUnitName() + defalutHouseOm.getHouseName());
                        memberDefalutHouseMap.put("agencyId", defalutHouseOm.getAgencyId());
                        memberDefalutHouseMap.put("isDefault",2);
                        memberHouseList.add(memberDefalutHouseMap);
                        defalutHouseOmTag = false;
                    }
                }//排除 管理员申请
            }
        }
        return memberHouseList;
    }

    /**
     * 查询 家庭成员
     *
     * @param memberId 会员id
     * @param houseId  户室id
     * @return
     */
    public List<Map<String, Object>> getFamilyMember(Long memberId, Long houseId) {
        List<Map<String, Object>> returnMap = new ArrayList<Map<String, Object>>();
        Wrapper<OwnerMember> familyMemberWp = new EntityWrapper<OwnerMember>();
        familyMemberWp.eq("house_id", houseId);
        familyMemberWp.eq("referrer_id", memberId);
        List<OwnerMember> familyMemberOmList = ownerMemberService.selectList(familyMemberWp);
        if (null != familyMemberOmList) {
            for (int x = 0; x < familyMemberOmList.size(); x++) {
                Map<String, Object> familyMemberMap = new HashMap<String, Object>();
                MemberInfo memberInfo = memberService.queryBymember(familyMemberOmList.get(x).getMemberId());
                if (memberInfo != null) {
                    familyMemberMap.put("memberNickName", memberInfo.getNickName());
                    familyMemberMap.put("memberId", memberInfo.getMemberId());
                    familyMemberMap.put("memberSex", memberInfo.getSex());
                    familyMemberMap.put("memberPortrait", memberInfo.getImg());
                    if (null == familyMemberMap.get("memberNickName")) {
                        familyMemberMap.put("memberNickName", "");
                    }
                    if (null == familyMemberMap.get("memberSex")) {
                        familyMemberMap.put("memberSex", 2);//性别保密
                    }
                    if (null == familyMemberMap.get("memberPortrait")) {
                        familyMemberMap.put("memberPortrait", "");
                    }
                    returnMap.add(familyMemberMap);
                }
            }
        }
        return returnMap;
    }

    /**
     * 生成 家庭成员 邀请码
     *
     * @return
     */
    public String getInviteCode() {
        String dateStr = DateUtil.format(new Date(), DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS);
        String code = dateStr.substring(dateStr.length() - 4, dateStr.length());//截取当前日期的分秒
        code = code + CodeGenerate.generateRandomStr(2).toLowerCase();//随机生成2位随机数作为邀请码
        //验证该邀请码是否存在
        Object testExist = redisCacheUtil.getVlue("validateHouseByInviteCode:" + code);
        if (testExist != null) {
            code = getInviteCode();
        }
        return code;
    }

    public String myHouseDescription() {
        StringBuilder descriptionStr = new StringBuilder("{");
        descriptionStr.append("communityId:社区id,communityName:社区名称,");
        descriptionStr.append("houseId:户室id,houseName:户室名称,");
        descriptionStr.append("agencyId:物业机构id,");
        descriptionStr.append("isDefault:是(2)/否(1)是默认房屋");
        descriptionStr.append("},");
        return descriptionStr.toString();
    }

    public String myFamilyMemberDescription() {
        StringBuilder descriptionStr = new StringBuilder("{");
        descriptionStr.append("memberNickName:会员昵称,memberId:会员id,memberSex:会员性别(0:女,1:男,2:保密),memberPortrait:会员头像,");
        descriptionStr.append("},");
        return descriptionStr.toString();
    }
}
